package org.mybatis.plus.boot;
 
import java.sql.Connection;

import javax.annotation.Resource;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.mybatis.plus.core.SqlSessionFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
 
/**
* @desc: Transaction切面
**/
@Aspect // 这是一个切面类，用来监测方法的调用，调用前判断是有@DefTransactional 注解
public class DataSourceTransactionManager {
	
	private SqlSessionFactory sqlSessionFactory;
	
    public DataSourceTransactionManager(SqlSessionFactory sqlSessionFactory) {
		super();
		this.sqlSessionFactory = sqlSessionFactory;
	}

	/**
     *通过@Pointcut注解声明频繁使用的切点表达式
     */
	@Pointcut("@annotation(org.mybatis.plus.annos.Transactional)")
    public void pointCut(){
 
    }
 
    /**
     * @description  在连接点执行之后执行的通知（返回通知和异常通知的异常）
     */
	// 定义需要匹配的切点表达式，同时需要匹配参数
    @Around("pointCut()")
    public Object around(ProceedingJoinPoint pjp) throws Throwable{
        System.out.println("方法环绕start...around");
        Object result = null;
        Connection connection = sqlSessionFactory.getConnection();
        try{
            result = pjp.proceed();
            System.out.println("commit=="+connection);
            connection.commit();
        }catch (Throwable e){
            e.printStackTrace();
            System.out.println("rollback=="+connection);
            connection.rollback();
        }finally {
        	 System.out.println("close=="+connection);
        	connection.close();
        }
        System.out.println("方法环绕end...around");
        return result;
    }
 
}